package com.ycxy.springsecuritycourse.service.impl;

import com.ycxy.springsecuritycourse.entity.LoginUser;
import com.ycxy.springsecuritycourse.entity.Users;
import com.ycxy.springsecuritycourse.mapper.RolesMapper;
import com.ycxy.springsecuritycourse.mapper.UsersMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class LoginUserDetailsService implements UserDetailsService {

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private RolesMapper rolesMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //通过username查询user
        Users user = usersMapper.getUserByUsername(username);
        if(user==null){
            throw new UsernameNotFoundException("用户不存在");
        }
        List<String> perssionList = rolesMapper.getRoleByUserId(user.getId());
        return new LoginUser(user,perssionList);
    }
}
